package mysql

import (
	"context"
	"github.com/go-redis/redis/v8"
	"gorm.io/gorm"
	"strconv"
)

type Cart struct {
	gorm.Model
	UserId     int64
	GoodsId    int64
	GoodsName  string
	GoodsNum   int64
	GoodsPrice float64
}

var st *redis.Client

func init() {
	st = redis.NewClient(&redis.Options{
		Addr:     "127.0.0.1:6379",
		Password: "",
		DB:       0,
	})
}

//type NewCart struct {
//	gorm.Model
//	Cart
//	NewGoodsPrice float64
//}

// TODO:加入购物车
func CreateCart(Cart Cart) Cart {
	db.Create(&Cart)
	return Cart
}

func AddCart(userid string, goodsid string, num int) {
	for i := 0; i < num; i++ {
		st.LPush(context.Background(), "userid "+userid, goodsid)
	}
}

// TODO：修改购物车
func EditCart(Cart Cart) Cart {
	db.Save(&Cart)
	return Cart
}

// Todo : 删除、移除购物车
func DelAll(userid string) map[string]int {
	num, _ := st.LRange(context.Background(), "userid "+userid, 0, -1).Result()
	m := map[string]int{}
	for _, s := range num {
		m[s]++
	}
	st.Del(context.Background(), "userid "+userid)
	return m
}

func DelPart(userid string, goodsid string, num int) {
	st.LRem(context.Background(), "userid "+userid, int64(num), goodsid)
}

// Todo :归还虚拟库存
func BackStock(userid string, goodsid string, num int) {
	for i := 0; i < num; i++ {
		st.LPush(context.Background(), "Virtual Inventory", goodsid)
	}
}

// TODO:获取购物车列表
func GetCartList(UserId int64) []*Cart {
	carts := []*Cart{}
	db.Where("user_id = ?", UserId).Find(&carts)
	return carts
}

// TODO:更新虚拟库存
func Update(goodsid int, num int) {
	st.LPush(context.Background(), "goodsid", goodsid)
	st.Set(context.Background(), "vnum "+strconv.Itoa(goodsid), num, 0)
}

// TODO：凌晨更新数据到数据库中
func UpdateMysql(goodsid string) {
	ids, _ := st.LRange(context.Background(), "goodsid", 0, -1).Result()
	m := map[string]int{}
	for _, id := range ids {
		if id == goodsid {
			m[goodsid]++
		}
	}
	g := Product{
		GoodsStock: int64(m[goodsid]),
	}
	num, _ := strconv.Atoi(goodsid)
	g.ID = uint(num)
	db.Save(&g)
}

func Search(goodsid string, nums int) string {
	all, _ := st.LRange(context.Background(), "Virtual Inventory", 0, -1).Result()
	m := map[string]int{}
	for _, s := range all {
		if s == goodsid {
			m[goodsid]++
		}
	}
	num := m[goodsid]
	if nums > num {
		return "0"
	}
	return "1"
}
